package com.zhoug.common.utils;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;

/**
 * @Author 35574
 * @Date 2020/4/24
 * @Description
 */
public class SpannableUtils {

    /**
     * 添加必填项的*号标记,并标红
     * @param required  required
     * @return Spannable
     */
    public static Spannable requiredText(CharSequence required){
        if(required!=null){
            String text = required.toString();
            SpannableString spannable;
            //文本中包含*,则*号标红
            int index = text.lastIndexOf("*");
            if(index>=0 && index<text.length()){
                spannable= new SpannableString(text);
                spannable.setSpan(new ForegroundColorSpan(Color.RED), index, index+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

            }else{
                //文本中不包含*

                if(text.endsWith(":")){
                    //冒号结尾
                    spannable= new SpannableString(text.substring(0,text.length()-1)+  "*:");
                    spannable.setSpan(new ForegroundColorSpan(Color.RED), spannable.length() - 2, spannable.length()-1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                }else{
                    //纯文本,添加*
                    spannable= new SpannableString(text+"*");
                    spannable.setSpan(new ForegroundColorSpan(Color.RED), spannable.length()-1, spannable.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                }
            }
            return spannable;
        }
        return null;
    }
}
